let mysql = require("mysql");
let config = require("../config/default.js");

let pool = mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  database: config.database.DATABASE,
});

// 查找数据
function Mysql(table) {
  let sql = "SELECT * from " + table
  return new Promise((resolve, reject) => {
    pool.query(sql, (error, results, fields) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(results);
    });
  });
}

// 添加数据
let addSql = (table, datas) => {
  let fields = "";
  let values = "";
  for (let k in datas) {
    fields += k + ",";
    values = values + "'" + datas[k] + "',";
  }
  console.log(fields, values);
  fields = fields.slice(0, -1);
  values = values.slice(0, -1);
  console.log(fields, values);
  let sql = "INSERT INTO " + table + "(" + fields + ") VALUES(" + values + ")";
  return new Promise((resolve, reject) => {
    pool.query(sql, (error, results) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(results);
    });
  });
};
// 修改数据
let xiuSql = function (table, sets, where) {
  let _SETS = "";
  let _WHERE = "";
  let keys = "";
  let values = "";
  for (let k in sets) {
    _SETS += k + "='" + sets[k] + "',";
  }
  _SETS = _SETS.slice(0, -1);
  for (let k2 in where) {
    //  _WHERE+=k2+"='"+where[k2]+"' AND ";
    _WHERE += k2 + "=" + where[k2];
  }
  // UPDATE user SET Password='321' WHERE UserId=12
  //update table set username='admin2',age='55'   where id="5";
  let sql = "UPDATE " + table + " SET " + _SETS + " WHERE " + _WHERE;
  console.log(sql);
  return new Promise((resolve, reject) => {
    pool.query(sql, (error, results) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(results);
    });
  });
};
// 删除数据
let remSql = function (table, where) {
  let _WHERE = "";
  for (let k2 in where) {
    //多个筛选条件使用  _WHERE+=k2+"='"+where[k2]+"' AND ";
    _WHERE += k2 + "=" + where[k2];
  }
  // DELETE  FROM user WHERE UserId=12
  let sql = "DELETE  FROM " + table + " WHERE " + _WHERE;
  return new Promise((resolve, reject) => {
    pool.query(sql, (error, results) => {
      if (error) {
        reject(error);
        return;
      }
      resolve(results);
    });
  });
};
module.exports = { Mysql, addSql, xiuSql, remSql };
